package com.kai.steering.exception;

import com.kai.steering.data.service.util.OfficeUtil;
import lombok.Data;
import lombok.ToString;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @ Author     ：LiuKai.
 * @ Date       ：Created in 10:44 2022-2-22
 * @ Description：通用异常
 * @ Modified By：
 * @Version:
 */
@Data
@ToString
public class UimpException extends RuntimeException {

    private HttpStatus status;
    private String code;
    private String message;


    public UimpException(HttpStatus status, String code, String message, Throwable exception) {
        super(exception);
        this.message = message;
        this.code = code;
        this.status = status;
    }

    public UimpException(HttpStatus status, String code, String message) {
        this(status, code, message, null);
    }
    /**
     * 生成异常信息文件
     * @param file
     * @param incorrectDataS
     * @return
     * @throws IOException
     */
    public static ResponseEntity generateResponse(MultipartFile file, List<ExcelException> incorrectDataS) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = OfficeUtil.excelChangeLattice(file.getInputStream(), incorrectDataS);
        // 创建HTTP头以进行下载
        String fileName =new Date().toString()+"_异常_"+ file.getOriginalFilename();

        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        headers.add("Content-Type", MediaType.APPLICATION_OCTET_STREAM_VALUE);
        // 将outputStream的内容转换为字节数组
        byte[] fileContent = byteArrayOutputStream.toByteArray();
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(fileContent, headers, HttpStatus.OK);
        return responseEntity;
    }
}
